<?php

/**
* @version 1.4 :: 20/01/2009
* @copyright (C) 2009 ZevS (http://myagi.info, icq# 132580)
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

// no direct access
defined( '_VALID_MOS' ) or die();

global $mosConfig_lang, $mosConfig_absolute_path;

if ($mosConfig_lang=='') {
$mthanks_language='russian';
} else {
$mthanks_language=$mosConfig_lang;
}
if ( file_exists( $mosConfig_absolute_path ."/mambots/content/mthanks/language/".$mthanks_language.".php" ) ) {
include_once($mosConfig_absolute_path.'/mambots/content/mthanks/language/'.$mthanks_language.'.php');
} else {
include_once($mosConfig_absolute_path.'/mambots/content/mthanks/language/russian.php');
}

$_MAMBOTS->registerFunction( 'onPrepareContent', 'botThanksLinks' );

function botThanksLinks( $published, &$row, &$params, $page = 0 ) {
	global $task, $my;

	$database = &database::getInstance();

	// check if param query has previously been processed
	if ( !isset($_MAMBOTS->_content_mambot_params['mThanks']) ) {
		// load mambot params info
		$query = "SELECT params"
		. "\n FROM #__mambots"
		. "\n WHERE element = 'mThanks'"
		. "\n AND folder = 'content'";
		$database->setQuery( $query );
		$database->loadObject($mambot);

		// save query to class variable
		$_MAMBOTS->_content_mambot_params['mThanks'] = $mambot;
	}
	// pull query data from class variable
	$mambot = $_MAMBOTS->_content_mambot_params['mThanks'];

	$botParams = new mosParameters( $mambot->params );
	$profile = $botParams->get( 'profile' );
	$show_guest = $botParams->get( 'showguest' );
	$show_front = $botParams->get( 'showfront' );

	if (!$row) {
		return;
	}

	$id = $row->id;

	if (!stristr($row->text, '{nothanks}')) {

		//проверяем на существование таблицы
		$database->setQuery("CREATE TABLE IF NOT EXISTS `#__mthanks` (`id` int(11) NOT NULL auto_increment, `cid` int(11) NOT NULL default '0', `uid` int(11) NOT NULL default '0', PRIMARY KEY  (`id`)) TYPE=MyISAM;");
		$database->query();
		//вывод в полной новости
		if ($task == 'view' && isset($row->created)) {
			//Выводим количество благодарностей и список пользователей
			$query = "SELECT COUNT(*) FROM #__mthanks WHERE cid = $id LIMIT 1";
			$database->setQuery( $query );
			$count = $database->loadRow();
			if($count[0]!=0){
				$row->text .= "<br> '._MT_THANK.' ".get_ending($count[0], '._MT_SAY.', array('', '._MT_END_ONE.', '._MT_END_TWO.'), false)." ".get_ending($count[0], '._MT_PEOPLE.', array('', '._MT_END_THREE.', '')).":<br>";
				//выводим список поблагодаривших
				$query = "SELECT b.id, b.cid, b.uid, a.name FROM #__mthanks AS b LEFT JOIN #__users AS a ON b.uid = a.id WHERE b.cid = $id";
				$database->setQuery( $query );
				$thxs = $database->loadObjectList();
				foreach ( $thxs as $thx1 ) {
					if($profile==1){
						$thx_member[] = '<a href="'.sefRelToAbs( 'index.php?option=com_users&task=profile&user='.$thx1->uid ).'">'.$thx1->name.'</a>';
					}else{
						$thx_member[] = $thx1->name;
					}
				}
				$row->text .= implode(', ',$thx_member);
			}else{
				$row->text .= _MT_THANKS_NOT_SAY;
			}

			//Выводим кнопку "сказать спасибо"
			if ($my->id) {
				mosCommonHTML::loadJquery();
				$row->text .= '<br><br><div id="mydiv'.$id.'" onclick="$(this).load('.'\''.Jconfig::getInstance()->config_live_site.'/mambots/content/mthanks/addthx.php'.'\''.', {cid:'.$id.', myid:'.$my->id.'}); return false;" style="cursor:pointer" class="thanks">'._MT_SAY_THANKS.'</div>';
			}elseif($show_guest==1){
				$row->text .= '<br><br><div>'._MT_THANKS_MAY_SAY_ONLY_REG.' . <a href="'.sefRelToAbs( "index.php?option=com_users&amp;task=register" ).'">'._MT_REG.'</a></div>';
			}
		}

		//показываем количество благодарностей в блогах
		if ($show_front == 1) {

			if ($task != 'view' && isset($row->created)) {
				$query = "SELECT COUNT(*) FROM #__mthanks WHERE cid = $id LIMIT 1";
				$database->setQuery( $query );
				$count = $database->loadRow();
				if ($count[0]){
					$text = '<span class="small">'._MT_THANKS.' ' . get_ending($count[0], '._MT_NUM.', array('', '._MT_END_THREE.', ''), true) . '</span>';
				}else{
					$text = '<span class="small">'._MT_NOT_THANKS.'</span>';
				}
				$row->text .= $text;
			}
		}
	}else{
		$row->text = preg_replace('#{nothanks}#i', '', $row->text);
	}
	return;
}

function get_ending(&$value, $word, $ends, $with_value = true) {

	if (count($ends) < 3) {
		return '';
	}
	$sv = (string)$value;
	$l = strlen($sv);
	$d1 = (int)$sv[$l - 1];
	$d2 = ($l >= 2 ? $sv[$l - 2] : '');
	$result = ($with_value ? $sv . ' ' : '');
	if ($sv == '0' || $d2 == '1' || ($d2 != '1' && (($d1 >= 5 && $d1 <= 9) || $d1 == 0))) {
		return $result . $word . $ends[2];
	}
	if ($d2 != '1' && $d1 >= 2 && $d1 <= 4) {
		return $result . $word . $ends[1];
	}
	if ($d2 != '1' && $d1 == 1) {
		return $result . $word . $ends[0];
	}
}